package org.magicsoft.office.docx4j;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.SpreadsheetMLPackage;
import org.docx4j.openpackaging.parts.SpreadsheetML.WorkbookPart;
import org.docx4j.openpackaging.parts.SpreadsheetML.WorksheetPart;
import org.magicsoft.office.exception.OfficeException;
import org.xlsx4j.exceptions.Xlsx4jException;
import org.xlsx4j.org.apache.poi.ss.usermodel.DataFormatter;
import org.xlsx4j.sml.Cell;
import org.xlsx4j.sml.Row;
import org.xlsx4j.sml.Sheet;

public class ExcelUtils {

	private WorkbookPart workbookPart = null;

	private Map<String, Integer> sheetIndexMap = null;

	private DataFormatter dataFormatter = new DataFormatter();

	public void openWorkbook(InputStream is) {
		try {
			SpreadsheetMLPackage spreadsheetMLPackage;
			spreadsheetMLPackage = (SpreadsheetMLPackage) SpreadsheetMLPackage.load(is);
			this.workbookPart = spreadsheetMLPackage.getWorkbookPart();
		} catch (Docx4JException e) {
			throw new OfficeException(e);
		}
	}

	public WorksheetPart getWorksheet(int index) {
		try {
			return this.workbookPart.getWorksheet(index);
		} catch (Xlsx4jException e) {
			throw new OfficeException(e);
		}
	}

	public WorksheetPart getWorksheet(String sheetName) {
		try {
			List<Sheet> sheets = this.workbookPart.getContents().getSheets().getSheet();

			int i = 0;
			this.sheetIndexMap = new HashMap<>();
			for (Sheet sheet : sheets) {
				this.sheetIndexMap.put(sheet.getName(), i++);
			}
			return this.getWorksheet(this.sheetIndexMap.get(sheetName));
		} catch (Docx4JException e) {
			throw new OfficeException(e);
		}
	}

	public List<Row> getRows(WorksheetPart worksheetPart) {
		try {
			return worksheetPart.getContents().getSheetData().getRow();
		} catch (Docx4JException e) {
			throw new OfficeException(e);
		}
	}

	public List<Cell> getCells(Row row) {
		return row.getC();
	}

	public String getCellValue(Cell cell) {
		if (cell.getV() == null) {
			return null;
		}
		return dataFormatter.formatCellValue(cell);
	}

	public WorkbookPart getWorkbookPart() {
		return this.workbookPart;
	}

}
